using FluentValidation;
using Microsoft.EntityFrameworkCore;
using ZhaoXi.MSACommerce.SharedKenel.Messaging;
using Zhaoxi.MSACommerce.StockService.Infrastructure;

namespace Zhaoxi.MSACommerce.StockService.UseCases.Commands;

public record CreateStockResvCommand(long SkuId, long OrderId, long Quantity) : ICommand<Result>;

public class CreateStockResvCommandValidator : AbstractValidator<CreateStockResvCommand>
{
    public CreateStockResvCommandValidator()
    {
        RuleFor(query => query.Quantity)
            .GreaterThan(0).WithMessage("数量必须大于0");
    }
}

public class CreateStockResvCommandHandler(StockDbContext
    dbContext) : ICommandHandler<CreateStockResvCommand,Result>
{
    public async Task<Result> Handle(CreateStockResvCommand request, CancellationToken cancellationToken)
    {
        //有问题
        var stock = await dbContext.SkuStocks.FirstOrDefaultAsync(s => s.Id == request.SkuId);
        
        if (stock is null) return Result.NotFound();

        stock. AddResvQty(request. OrderId, qty: request. Quantity, exprMinutes: 30);
        
        await dbContext.SaveChangesAsync(cancellationToken);
        return stock.AvailQty < request. Quantity ? Result.Failure("库存不足") : Result.Success(); 
    }
}